// pages/home/index.ts
import { getAchievementByDays, getLastCheckinDaysAgo } from '../../utils/util';
import { getStorage, setStorage } from '../../utils/storage';
import type { UserInfo } from '@/types/user';

const now = new Date();

const defaultUser: UserInfo = {
  nickName: '未授权用户',
  avatarUrl: 'https://via.placeholder.com/80',
  isAlive: true,
  firstCheckinDate: now,
  lastCheckinDate: now,
  daysAlive: 0,
};

Page({
  data: {
    userInfo: defaultUser,
    aliveText: '💀 我还活着！',
    achievements: '',
    daysToDeath: 3,
  },

  async onLoad() {
    const app = getApp<IAppOption>();
    const cachedUser = getStorage<UserInfo>('userInfo');

    if (cachedUser) {
      const updatedUser = this.processUserInfo(cachedUser);
      console.log("cachedUser:",updatedUser);
      this.setData({
        userInfo: updatedUser,
        achievements: getAchievementByDays(updatedUser.daysAlive),
      });
    }

    if (app.globalData.userId) {
      await this.loadUserFromDB(app.globalData.userId);
    } else {
      app.openidReadyCallback = async (openid: string) => {
        await this.loadUserFromDB(openid);
      };
    }
  },

  async loadUserFromDB(openid: string) {
    try {
      const res = await wx.cloud.callFunction({
        name: 'user_operate',
        data: {
          action: 'getUser',
          openid: openid  // 传入openid
        }
      });
  
      if (res.result.success && res.result.user) {
        const dbUser = res.result.user;
        const updatedUser = this.processUserInfo(dbUser);
        setStorage('userInfo', updatedUser);
        this.setData({
          userInfo: updatedUser,
          achievements: getAchievementByDays(updatedUser.daysAlive),
        });
      } else {
        // 用户不存在时，不强制覆盖已有 userInfo（比如缓存用户）
        console.warn('云函数未返回用户信息，使用默认值');
      }
    } catch (err) {
      console.error('调用 user_operate 获取用户失败：', err);
    }
  },

  processUserInfo(user: UserInfo): UserInfo & { lastCheckin: string; isAlive: boolean } {
    const now = new Date();
    const lastDate = new Date(user.lastCheckinDate);
  
    const daysSinceLastCheckin = Math.floor((now.getTime() - lastDate.getTime()) / (1000 * 60 * 60 * 24));
    const DEAD_THRESHOLD = 3;
  
    const isAlive = daysSinceLastCheckin < DEAD_THRESHOLD;
    const totalAliveDays = isAlive ? user.daysAlive + daysSinceLastCheckin : user.daysAlive;
  
    const lastCheckin = getLastCheckinDaysAgo(lastDate);
  
    // 更新页面 aliveText
    const aliveText = isAlive ? '💀 我还活着！' : '☠️ 立即复活';
  
    this.setData({
      aliveText
    });
  
    return {
      ...user,
      isAlive,
      daysAlive: totalAliveDays,
      lastCheckinDate: lastDate,
      lastCheckin
    };
  },
  

  async onAliveTap() {
    try {
      // 1. 获取用户 profile（必须用户点击触发）
      const userProfile = await wx.getUserProfile({
        desc: '完善用户资料',
      });
  
      // 2. 获取 openid
      const app = getApp<IAppOption>();
      const openid = app.globalData.userId;
  
      // 3. 调用整合后的事务云函数
      const res = await wx.cloud.callFunction({
        name: 'checkin_with_user_update',
        data: {
          openid,
          userInfo: {
            nickName: userProfile.userInfo.nickName,
            avatarUrl: userProfile.userInfo.avatarUrl
          }
        }
      });
  
      if (!res.result.success) {
        wx.showToast({ title: res.result.message || '打卡失败', icon: 'none' });
        return;
      }
  
      // 4. 成功后更新本地展示
      const updatedUser: UserInfo = res.result.userInfo;
  
      const processedUser = this.processUserInfo(updatedUser);
      setStorage('userInfo', processedUser);
  
      this.setData({
        userInfo: processedUser,
        achievements: getAchievementByDays(processedUser.daysAlive),
      });
  
      wx.showToast({ title: '打卡成功！', icon: 'success' });
  
    } catch (err) {
      console.error('打卡失败', err);
      wx.showToast({ title: '打卡失败，请稍后再试', icon: 'none' });
    }
  },
  
  

  toAchievement() {
    wx.navigateTo({
      url: '/pages/achievement/index',
    });
  },
});
